<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三国战棋Roguelike</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#9D2932',      // 三国红
                        secondary: '#2D4262',    // 深蓝
                        neutral: '#E8C07D',      // 金色
                        dark: '#1C1C1C',         // 深色
                        light: '#F8F4E3'         // 浅色
                    },
                    fontFamily: {
                        sans: ['SimSun', 'serif']
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .game-shadow {
                box-shadow: 0 0 15px rgba(0, 0, 0, 0.3);
            }
            .grid-cell {
                @apply w-14 h-14 border border-gray-300 flex items-center justify-center transition-all duration-200;
            }
            .grid-cell-highlight {
                @apply bg-primary/20 cursor-pointer;
            }
            .grid-cell-move {
                @apply bg-blue-100 ring-2 ring-blue-500 cursor-pointer;
            }
            .grid-cell-attack {
                @apply bg-red-100 ring-2 ring-red-500 cursor-pointer;
            }
            .character {
                @apply w-12 h-12 rounded-full flex items-center justify-center text-white font-bold transition-all duration-300 shadow-md relative cursor-pointer;
            }
            .character-selected {
                @apply scale-110 ring-4 ring-yellow-400 z-10;
            }
            .character-hurt {
                animation: hurt 0.5s;
            }
            .character-moving {
                animation: move 0.3s;
            }
            .character-dying {
                animation: die 1s forwards;
            }
            .btn-game {
                @apply bg-primary text-white py-2 px-4 rounded-md hover:bg-primary/80 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary/50 transform hover:scale-105 active:scale-95;
            }
            .damage-indicator {
                position: absolute;
                color: #dc2626;
                font-weight: bold;
                pointer-events: none;
                animation: float-up 1s forwards;
            }
            .heal-indicator {
                position: absolute;
                color: #16a34a;
                font-weight: bold;
                pointer-events: none;
                animation: float-up 1s forwards;
            }
            .notification {
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                padding: 10px 20px;
                background-color: rgba(0, 0, 0, 0.8);
                color: white;
                border-radius: 5px;
                z-index: 100;
                opacity: 0;
                transition: opacity 0.3s;
            }
            .notification.show {
                opacity: 1;
            }
            .tooltip {
                position: absolute;
                background-color: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 5px 10px;
                border-radius: 3px;
                font-size: 12px;
                z-index: 50;
                pointer-events: none;
                opacity: 0;
                transition: opacity 0.2s;
                white-space: nowrap;
            }
            .event-popup {
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background-color: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
                z-index: 1000;
                max-width: 80%;
                width: 400px;
            }
            .event-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(0, 0, 0, 0.7);
                z-index: 999;
            }
            .perk {
                @apply bg-gray-100 p-3 rounded-md mb-2 cursor-pointer hover:bg-gray-200 transition-colors border-l-4 border-primary;
            }
            .loading-screen {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: #F8F4E3;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                z-index: 2000;
            }
            .loading-spinner {
                width: 50px;
                height: 50px;
                border: 5px solid #E8C07D;
                border-top: 5px solid #9D2932;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin-bottom: 20px;
            }
        }

        @keyframes hurt {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(0.8) rotate(5deg); background-color: #ef4444; }
        }
        
        @keyframes move {
            0% { transform: scale(0.8); opacity: 0.7; }
            100% { transform: scale(1); opacity: 1; }
        }
        
        @keyframes float-up {
            0% { transform: translateY(0); opacity: 1; }
            100% { transform: translateY(-30px); opacity: 0; }
        }
        
        @keyframes die {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2) rotate(10deg); }
            100% { transform: scale(0); opacity: 0; }
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 滚动条美化 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
    </style>
</head>
<body class="bg-light min-h-screen font-sans">
    <!-- 加载屏幕 -->
    <div id="loading-screen" class="loading-screen">
        <div class="loading-spinner"></div>
        <h2 class="text-primary text-xl font-bold">加载游戏资源中...</h2>
        <p id="loading-status" class="text-gray-600 mt-2">初始化音效系统...</p>
    </div>
    
    <!-- 通知提示 -->
    <div id="notification" class="notification"></div>
    
    <!-- 事件弹窗 -->
    <div id="event-overlay" class="event-overlay hidden"></div>
    <div id="event-popup" class="event-popup hidden">
        <h3 id="event-title" class="text-xl font-bold text-primary mb-3"></h3>
        <p id="event-description" class="mb-4"></p>
        <div id="event-choices" class="space-y-2"></div>
    </div>
    
    <div class="container mx-auto p-4 max-w-6xl">
        <!-- 游戏标题 -->
        <header class="text-center my-6">
            <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-primary tracking-wide">
                <span class="relative inline-block">
                    三国战棋
                    <span class="absolute -bottom-1 left-0 w-full h-1 bg-neutral rounded-full"></span>
                </span>
                <span class="text-secondary ml-2">Roguelike</span>
            </h1>
            <p class="text-gray-600 mt-3 italic">随机地图 · 策略战斗 · 武将养成 · 永久死亡</p>
        </header>

        <!-- 游戏状态面板 -->
        <div class="flex flex-col md:flex-row justify-between mb-6 gap-4">
            <div class="bg-white rounded-lg p-4 game-shadow flex-1 transform transition-all duration-300 hover:shadow-lg">
                <h2 class="text-lg font-bold text-secondary flex items-center">
                    <i class="fa fa-map-signs mr-2"></i>当前关卡: <span id="level" class="ml-1 font-bold text-primary">1</span>
                </h2>
                <p class="text-gray-600 mt-1">剩余敌人: <span id="enemy-count" class="font-bold text-red-500">3</span></p>
                <div class="mt-2 w-full bg-gray-200 rounded-full h-2.5">
                    <div id="level-progress" class="bg-primary h-2.5 rounded-full" style="width: 0%"></div>
                </div>
                <p class="text-xs text-gray-500 mt-1">距离下一关: <span id="progress-text">0%</span></p>
            </div>
            
            <div class="bg-white rounded-lg p-4 game-shadow flex-1 transform transition-all duration-300 hover:shadow-lg">
                <h2 class="text-lg font-bold text-secondary flex items-center">
                    <i class="fa fa-user mr-2"></i>我方武将
                </h2>
                <div id="player-party" class="flex flex-wrap gap-2 mt-2">
                    <!-- 武将状态会动态更新 -->
                </div>
            </div>
        </div>

        <!-- 游戏主区域 -->
        <div class="flex flex-col lg:flex-row gap-6">
            <!-- 游戏地图 -->
            <div class="flex-1 bg-white rounded-lg p-4 game-shadow transform transition-all duration-300 hover:shadow-lg">
                <div class="flex justify-between items-center mb-3">
                    <h2 class="font-bold text-secondary flex items-center">
                        <i class="fa fa-map mr-2"></i>战场地图
                    </h2>
                    <div id="turn-indicator" class="px-3 py-1 bg-primary text-white text-sm rounded-full">
                        玩家回合
                    </div>
                </div>
                <div id="game-map" class="grid grid-cols-10 gap-0 mx-auto w-fit relative"></div>
                
                <!-- 操作提示 -->
                <div class="mt-4 p-2 bg-gray-100 rounded text-sm text-gray-600">
                    <p><i class="fa fa-keyboard-o mr-1"></i> 快捷键: <kbd class="px-1.5 py-0.5 bg-gray-200 rounded text-xs">M</kbd> 移动 <kbd class="px-1.5 py-0.5 bg-gray-200 rounded text-xs">A</kbd> 攻击 <kbd class="px-1.5 py-0.5 bg-gray-200 rounded text-xs">E</kbd> 结束回合</p>
                </div>
            </div>

            <!-- 游戏信息与控制 -->
            <div class="lg:w-80 bg-white rounded-lg p-4 game-shadow transform transition-all duration-300 hover:shadow-lg">
                <h2 class="text-lg font-bold text-secondary mb-4 flex items-center">
                    <i class="fa fa-info-circle mr-2"></i>游戏信息
                </h2>
                
                <div id="selected-info" class="mb-6 p-3 bg-gray-100 rounded min-h-[100px] flex items-center justify-center">
                    <p class="text-gray-500">请选择一个角色或格子</p>
                </div>
                
                <div class="space-y-3">
                    <button id="move-btn" class="btn-game w-full flex items-center justify-center">
                        <i class="fa fa-arrows mr-2"></i>移动 (M)
                    </button>
                    <button id="attack-btn" class="btn-game w-full flex items-center justify-center bg-red-600">
                        <i class="fa fa-crosshairs mr-2"></i>攻击 (A)
                    </button>
                    <button id="ability-btn" class="btn-game w-full flex items-center justify-center bg-purple-600">
                        <i class="fa fa-bolt mr-2"></i>技能
                    </button>
                    <button id="end-turn-btn" class="btn-game w-full flex items-center justify-center bg-secondary">
                        <i class="fa fa-clock-o mr-2"></i>结束回合 (E)
                    </button>
                    <button id="new-game-btn" class="btn-game w-full flex items-center justify-center bg-green-600 mt-4">
                        <i class="fa fa-refresh mr-2"></i>新游戏
                    </button>
                </div>
                
                <div class="mt-6 pt-4 border-t border-gray-200">
                    <h3 class="font-bold text-secondary mb-2">游戏说明</h3>
                    <ul class="text-sm text-gray-600 space-y-1">
                        <li><i class="fa fa-circle text-xs text-primary mr-1"></i> 红色: 我方武将</li>
                        <li><i class="fa fa-circle text-xs text-red-500 mr-1"></i> 敌军</li>
                        <li><i class="fa fa-circle text-xs text-yellow-500 mr-1"></i> 物品/道具</li>
                        <li><i class="fa fa-circle text-xs text-blue-500 mr-1"></i> 特殊事件</li>
                        <li><i class="fa fa-circle text-xs text-gray-400 mr-1"></i> 障碍物</li>
                    </ul>
                </div>
                
                <div class="mt-6 pt-4 border-t border-gray-200">
                    <h3 class="font-bold text-secondary mb-2 flex items-center">
                        <i class="fa fa-volume-up mr-2"></i>音效控制
                    </h3>
                    <div class="flex items-center">
                        <button id="toggle-sound" class="text-gray-600 hover:text-primary transition-colors">
                            <i class="fa fa-volume-up text-xl"></i>
                        </button>
                        <input type="range" id="volume-control" min="0" max="100" value="70" 
                               class="ml-3 w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-primary">
                    </div>
                    <button id="test-sound" class="mt-2 text-sm text-primary hover:underline">测试音效</button>
                </div>
            </div>
        </div>

        <!-- 游戏日志 -->
        <div class="mt-6 bg-white rounded-lg p-4 game-shadow transform transition-all duration-300 hover:shadow-lg">
            <h2 class="text-lg font-bold text-secondary mb-2 flex items-center">
                <i class="fa fa-history mr-2"></i>战斗日志
            </h2>
            <div id="game-log" class="h-32 overflow-y-auto text-sm text-gray-700 bg-gray-50 p-3 rounded"></div>
        </div>
    </div>

    <script>
        // 音效管理 - 修复声音问题
        const SoundManager = {
            sounds: {
                move: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-arcade-mechanical-bling-210.mp3'),
                attack: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-sword-unsheath-3775.mp3'),
                hit: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-player-hit-in-a-game-2012.mp3'),
                heal: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-positive-interface-beep-221.mp3'),
                victory: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-achievement-bell-600.mp3'),
                defeat: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-player-losing-or-failing-2042.mp3'),
                select: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-select-click-1109.mp3'),
                turn: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-unlocking-563.mp3'),
                levelup: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-achievement-bell-600.mp3'),
                item: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-unlocking-563.mp3'),
                event: new Audio('https://assets.mixkit.co/sfx/preview/mixkit-mystery-unsheath-2759.mp3')
            },
            music: new Audio('https://assets.mixkit.co/music/preview/mixkit-epic-battle-music-689.mp3'),
            soundEnabled: true,
            musicEnabled: true,
            volume: 0.7,
            loadStatus: 0,
            totalSounds: 0,
            
            init() {
                // 计算总音效数量
                this.totalSounds = Object.keys(this.sounds).length + 1; // +1 是背景音乐
                this.loadStatus = 0;
                
                // 为每个音效添加加载完成事件
                Object.values(this.sounds).forEach(sound => {
                    sound.volume = this.volume;
                    sound.preload = 'auto';
                    
                    // 监听加载事件，更新加载状态
                    sound.addEventListener('canplaythrough', () => {
                        this.loadStatus++;
                        this.updateLoadingScreen();
                    }, { once: true });
                    
                    // 处理加载错误
                    sound.addEventListener('error', (e) => {
                        console.error('音效加载错误:', e);
                        this.loadStatus++;
                        this.updateLoadingScreen();
                    }, { once: true });
                });
                
                // 设置背景音乐
                this.music.volume = this.volume * 0.3;
                this.music.loop = true;
                this.music.preload = 'auto';
                
                this.music.addEventListener('canplaythrough', () => {
                    this.loadStatus++;
                    this.updateLoadingScreen();
                }, { once: true });
                
                this.music.addEventListener('error', (e) => {
                    console.error('背景音乐加载错误:', e);
                    this.loadStatus++;
                    this.updateLoadingScreen();
                }, { once: true });
                
                // 添加音量控制事件
                document.getElementById('volume-control').addEventListener('input', (e) => {
                    this.setVolume(e.target.value / 100);
                });
                
                // 添加音效开关事件
                document.getElementById('toggle-sound').addEventListener('click', () => {
                    this.toggleSound();
                });
                
                // 添加音效测试按钮
                document.getElementById('test-sound').addEventListener('click', () => {
                    this.testAllSounds();
                });
            },
            
            updateLoadingScreen() {
                const progress = Math.round((this.loadStatus / this.totalSounds) * 100);
                document.getElementById('loading-status').textContent = `加载资源: ${progress}%`;
                
                // 所有资源加载完成
                if (this.loadStatus >= this.totalSounds) {
                    setTimeout(() => {
                        document.getElementById('loading-screen').style.opacity = '0';
                        setTimeout(() => {
                            document.getElementById('loading-screen').style.display = 'none';
                            this.playMusic();
                        }, 500);
                    }, 500);
                }
            },
            
            setVolume(volume) {
                this.volume = volume;
                Object.values(this.sounds).forEach(sound => {
                    sound.volume = volume;
                });
                this.music.volume = volume * 0.3;
            },
            
            toggleSound() {
                this.soundEnabled = !this.soundEnabled;
                this.musicEnabled = !this.musicEnabled;
                
                const icon = document.querySelector('#toggle-sound i');
                if (this.soundEnabled) {
                    icon.classList.remove('fa-volume-off');
                    icon.classList.add('fa-volume-up');
                    this.playMusic();
                    showNotification('音效已开启');
                } else {
                    icon.classList.remove('fa-volume-up');
                    icon.classList.add('fa-volume-off');
                    this.music.pause();
                    showNotification('音效已关闭');
                }
            },
            
            play(soundName) {
                if (this.soundEnabled && this.sounds[soundName]) {
                    try {
                        // 克隆音频对象以允许同时播放同一音效
                        const sound = this.sounds[soundName].cloneNode();
                        sound.play();
                    } catch (e) {
                        console.log('音频播放失败:', soundName, e);
                        showNotification(`音效播放失败: ${soundName}`);
                    }
                }
            },
            
            playMusic() {
                if (this.musicEnabled) {
                    try {
                        this.music.play();
                    } catch (e) {
                        console.log('背景音乐播放失败:', e);
                        // 尝试用户交互后再播放
                        document.body.addEventListener('click', () => {
                            this.music.play().catch(err => console.log('仍无法播放背景音乐:', err));
                        }, { once: true });
                    }
                }
            },
            
            testAllSounds() {
                showNotification('测试音效...');
                this.play('select');
                setTimeout(() => this.play('move'), 300);
                setTimeout(() => this.play('attack'), 600);
                setTimeout(() => this.play('hit'), 900);
                setTimeout(() => this.play('heal'), 1200);
                setTimeout(() => this.play('victory'), 1500);
            }
        };

        // 游戏配置
        const GAME_CONFIG = {
            mapSize: 10,          // 10x10的地图
            playerCount: 3,       // 初始玩家数量
            enemyCount: 3,        // 每关敌人数量
            obstacleRate: 0.15,   // 障碍物比例
            itemRate: 0.1,        // 物品比例
            eventRate: 0.05       // 事件比例
        };

        // 游戏状态
        const gameState = {
            level: 1,
            currentPlayer: 0,     // 当前操作的玩家索引
            selectedCell: null,   // 选中的格子
            selectedCharacter: null, // 选中的角色
            turn: 'player',       // 回合: player 或 enemy
            characters: [],       // 所有角色
            map: [],              // 地图数据
            levelProgress: 0,     // 关卡进度(0-100)
            gameOver: false,      // 游戏是否结束
            seed: Math.random()   // 随机种子，用于生成地图
        };

        // 角色类型
        const CHARACTER_TYPES = {
            PLAYER: 'player',
            ENEMY: 'enemy'
        };

        // 格子类型
        const CELL_TYPES = {
            EMPTY: 'empty',
            OBSTACLE: 'obstacle',
            ITEM: 'item',
            EVENT: 'event'
        };

        // 物品类型
        const ITEM_TYPES = {
            POTION: 'potion',
            WEAPON: 'weapon',
            ARMOR: 'armor',
            TREASURE: 'treasure',
            SCROLL: 'scroll'
        };

        // 事件类型
        const EVENT_TYPES = {
            MERCHANT: 'merchant',
            SHRINE: 'shrine',
            TREASURE_ROOM: 'treasure_room',
            AMBUSH: 'ambush',
            TRAINER: 'trainer',
            MYSTERY: 'mystery'
        };

        // 技能列表
        const ABILITIES = {
            刘备: [
                {name: '仁德', description: '恢复周围友军10点生命值', cooldown: 3},
                {name: '义勇', description: '提升自身和相邻友军的防御力2回合', cooldown: 4}
            ],
            关羽: [
                {name: '青龙斩', description: '对单个敌人造成150%伤害', cooldown: 2},
                {name: '忠义', description: '保护相邻的友军，承受他们受到的伤害', cooldown: 5}
            ],
            张飞: [
                {name: '咆哮', description: '对周围所有敌人造成少量伤害并震慑他们', cooldown: 3},
                {name: '破胆', description: '使单个敌人下一回合无法行动', cooldown: 4}
            ],
            曹操: [
                {name: '奸雄', description: '攻击后恢复自身造成伤害的30%', cooldown: 3},
                {name: '号令', description: '提升周围友军的攻击力1回合', cooldown: 4}
            ],
            夏侯惇: [
                {name: '刚烈', description: '受到攻击时反弹20%伤害', cooldown: 3},
                {name: '奋不顾身', description: '对敌人造成大量伤害，但自身也受到少量伤害', cooldown: 4}
            ],
            典韦: [
                {name: '护主', description: '替相邻友军承受伤害', cooldown: 5},
                {name: '狂怒', description: '自身生命值越低，造成的伤害越高', cooldown: 0}
            ]
        };

        // 初始化游戏
        function initGame() {
            // 显示加载屏幕
            document.getElementById('loading-screen').style.display = 'flex';
            
            // 初始化音效系统
            SoundManager.init();
            
            // 重置游戏状态
            gameState.level = 1;
            gameState.gameOver = false;
            gameState.turn = 'player';
            gameState.seed = Math.random();
            
            generateMap();
            spawnCharacters();
            renderMap();
            updateGameInfo();
            updatePlayerPartyDisplay();
            addEventListeners();
            
            showNotification('欢迎来到三国战棋Roguelike！');
            logMessage('游戏开始！');
        }

        // 生成随机地图 - 增强Roguelike元素
        function generateMap() {
            gameState.map = [];
            gameState.levelProgress = 0;
            updateLevelProgress();
            
            // 使用种子确保随机数生成的一致性
            const seed = gameState.seed;
            let rand = mulberry32(seed);
            
            for (let y = 0; y < GAME_CONFIG.mapSize; y++) {
                const row = [];
                for (let x = 0; x < GAME_CONFIG.mapSize; x++) {
                    // 避免在玩家和敌人初始位置生成障碍物或事件
                    const isPlayerSpawnArea = (x < 3 && y < 3);
                    const isEnemySpawnArea = (x > 6 && y > 6);
                    
                    if (isPlayerSpawnArea || isEnemySpawnArea) {
                        row.push({ type: CELL_TYPES.EMPTY });
                        continue;
                    }
                    
                    // 随机生成内容
                    const r = rand();
                    if (r < GAME_CONFIG.obstacleRate) {
                        row.push({ type: CELL_TYPES.OBSTACLE });
                    } else if (r < GAME_CONFIG.obstacleRate + GAME_CONFIG.eventRate) {
                        // 随机事件
                        const eventTypes = Object.values(EVENT_TYPES);
                        const randomEvent = eventTypes[Math.floor(rand() * eventTypes.length)];
                        row.push({ 
                            type: CELL_TYPES.EVENT,
                            eventType: randomEvent
                        });
                    } else if (r < GAME_CONFIG.obstacleRate + GAME_CONFIG.eventRate + GAME_CONFIG.itemRate) {
                        // 随机物品
                        const itemTypes = Object.values(ITEM_TYPES);
                        const randomItem = itemTypes[Math.floor(rand() * itemTypes.length)];
                        row.push({ 
                            type: CELL_TYPES.ITEM,
                            itemType: randomItem
                        });
                    } else {
                        row.push({ type: CELL_TYPES.EMPTY });
                    }
                }
                gameState.map.push(row);
            }
            
            logMessage(`生成了第${gameState.level}关地图`);
        }

        // 生成角色 - 增强Roguelike元素
        function spawnCharacters() {
            gameState.characters = [];
            
            // 生成玩家角色（左上角）
            const playerPositions = [
                {x: 1, y: 1},
                {x: 2, y: 1},
                {x: 1, y: 2}
            ];
            
            const playerNames = ['刘', '关', '张'];
            const playerColors = ['bg-primary', 'bg-secondary', 'bg-green-600'];
            const fullNames = ['刘备', '关羽', '张飞'];
            
            for (let i = 0; i < GAME_CONFIG.playerCount; i++) {
                // 根据关卡提升属性
                const levelBoost = (gameState.level - 1) * 10;
                
                // 随机属性波动，增加Roguelike随机性
                const hpVariance = Math.floor(Math.random() * 10) - 5;
                const attackVariance = Math.floor(Math.random() * 3) - 1;
                
                // 获取角色技能
                const abilities = ABILITIES[fullNames[i]].map(ability => ({
                    ...ability,
                    currentCooldown: 0
                }));
                
                gameState.characters.push({
                    id: `player-${i}`,
                    type: CHARACTER_TYPES.PLAYER,
                    name: playerNames[i],
                    fullName: fullNames[i],
                    color: playerColors[i],
                    x: playerPositions[i].x,
                    y: playerPositions[i].y,
                    hp: 100 + i * 20 + levelBoost + hpVariance,
                    maxHp: 100 + i * 20 + levelBoost + hpVariance,
                    attack: 10 + i * 5 + Math.floor(levelBoost / 3) + attackVariance,
                    defense: 5 + i * 2 + Math.floor(levelBoost / 5),
                    moved: false,
                    level: 1 + Math.floor((gameState.level - 1) / 3),
                    experience: 0,
                    nextLevelExp: 100 * (1 + Math.floor((gameState.level - 1) / 3)),
                    abilities: abilities
                });
            }
            
            // 生成敌人（右下角）
            // 根据关卡变化敌人类型和数量
            const enemyCount = Math.max(GAME_CONFIG.enemyCount, Math.floor(gameState.level / 2) + 2);
            const enemyPositions = [];
            
            // 随机生成敌人位置（右下角区域）
            while (enemyPositions.length < enemyCount) {
                const x = 7 + Math.floor(Math.random() * 3);
                const y = 7 + Math.floor(Math.random() * 3);
                
                // 检查位置是否已存在
                if (!enemyPositions.some(pos => pos.x === x && pos.y === y)) {
                    enemyPositions.push({x, y});
                }
            }
            
            // 敌人类型池，随关卡增加更多种类
            const enemyTypes = [
                {names: ['曹', '曹操'], color: 'bg-red-500'},
                {names: ['夏侯', '夏侯惇'], color: 'bg-orange-500'},
                {names: ['典', '典韦'], color: 'bg-red-700'}
            ];
            
            // 高等级增加更强敌人
            if (gameState.level > 3) {
                enemyTypes.push(
                    {names: ['许', '许褚'], color: 'bg-red-600'},
                    {names: ['张', '张辽'], color: 'bg-indigo-600'}
                );
            }
            
            if (gameState.level > 5) {
                enemyTypes.push(
                    {names: ['吕', '吕布'], color: 'bg-purple-600'} // 更强的精英敌人
                );
            }
            
            for (let i = 0; i < enemyCount; i++) {
                // 随机选择敌人类型
                const enemyType = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];
                
                // 根据关卡提升属性
                const levelBoost = (gameState.level - 1) * 10;
                
                // 精英敌人有额外属性加成
                const isElite = enemyType.names[1] === '吕布' || (gameState.level > 2 && Math.random() < 0.2);
                const eliteBoost = isElite ? 20 : 0;
                
                // 获取角色技能
                const abilities = ABILITIES[enemyType.names[1]] ? 
                    ABILITIES[enemyType.names[1]].map(ability => ({
                        ...ability,
                        currentCooldown: 0
                    })) : [];
                
                gameState.characters.push({
                    id: `enemy-${i}`,
                    type: CHARACTER_TYPES.ENEMY,
                    name: enemyType.names[0],
                    fullName: enemyType.names[1],
                    color: enemyType.color,
                    x: enemyPositions[i].x,
                    y: enemyPositions[i].y,
                    hp: 80 + levelBoost + eliteBoost,
                    maxHp: 80 + levelBoost + eliteBoost,
                    attack: 8 + Math.floor(levelBoost / 3) + (isElite ? 5 : 0),
                    defense: 3 + Math.floor(levelBoost / 5) + (isElite ? 3 : 0),
                    isElite: isElite,
                    abilities: abilities
                });
            }
        }

        // 渲染地图 - 优化操作体验
        function renderMap() {
            const mapContainer = document.getElementById('game-map');
            mapContainer.innerHTML = '';
            
            // 渲染每个格子
            for (let y = 0; y < GAME_CONFIG.mapSize; y++) {
                for (let x = 0; x < GAME_CONFIG.mapSize; x++) {
                    const cell = document.createElement('div');
                    cell.classList.add('grid-cell');
                    cell.dataset.x = x;
                    cell.dataset.y = y;
                    
                    // 根据格子类型设置样式
                    const mapCell = gameState.map[y][x];
                    if (mapCell.type === CELL_TYPES.OBSTACLE) {
                        cell.classList.add('bg-gray-300');
                        cell.innerHTML = '<i class="fa fa-mountain text-gray-500"></i>';
                    } else if (mapCell.type === CELL_TYPES.ITEM) {
                        cell.classList.add('bg-yellow-100');
                        // 根据物品类型显示不同图标
                        switch(mapCell.itemType) {
                            case ITEM_TYPES.POTION:
                                cell.innerHTML = '<i class="fa fa-flask text-yellow-600"></i>';
                                break;
                            case ITEM_TYPES.WEAPON:
                                cell.innerHTML = '<i class="fa fa-sword text-yellow-600"></i>';
                                break;
                            case ITEM_TYPES.ARMOR:
                                cell.innerHTML = '<i class="fa fa-shield text-yellow-600"></i>';
                                break;
                            case ITEM_TYPES.TREASURE:
                                cell.innerHTML = '<i class="fa fa-diamond text-yellow-600"></i>';
                                break;
                            case ITEM_TYPES.SCROLL:
                                cell.innerHTML = '<i class="fa fa-scroll text-yellow-600"></i>';
                                break;
                        }
                    } else if (mapCell.type === CELL_TYPES.EVENT) {
                        cell.classList.add('bg-blue-100');
                        // 根据事件类型显示不同图标
                        switch(mapCell.eventType) {
                            case EVENT_TYPES.MERCHANT:
                                cell.innerHTML = '<i class="fa fa-shopping-cart text-blue-600"></i>';
                                break;
                            case EVENT_TYPES.SHRINE:
                                cell.innerHTML = '<i class="fa fa-star text-blue-600"></i>';
                                break;
                            case EVENT_TYPES.TREASURE_ROOM:
                                cell.innerHTML = '<i class="fa fa-chest text-blue-600"></i>';
                                break;
                            case EVENT_TYPES.AMBUSH:
                                cell.innerHTML = '<i class="fa fa-crosshairs text-blue-600"></i>';
                                break;
                            case EVENT_TYPES.TRAINER:
                                cell.innerHTML = '<i class="fa fa-graduation-cap text-blue-600"></i>';
                                break;
                            default:
                                cell.innerHTML = '<i class="fa fa-question text-blue-600"></i>';
                        }
                    }
                    
                    // 检查是否有角色在这个格子上
                    const character = getCharacterAtPosition(x, y);
                    if (character) {
                        const charElement = document.createElement('div');
                        charElement.classList.add('character', character.color);
                        charElement.textContent = character.name;
                        charElement.title = `${character.fullName} (HP: ${character.hp}/${character.maxHp})`;
                        charElement.dataset.id = character.id;
                        
                        // 精英敌人标记
                        if (character.isElite) {
                            const eliteMarker = document.createElement('div');
                            eliteMarker.classList.add('absolute', 'top-0', 'right-0', 'w-2', 'h-2', 'bg-yellow-300', 'rounded-full');
                            charElement.appendChild(eliteMarker);
                        }
                        
                        // 添加HP条
                        const hpBarContainer = document.createElement('div');
                        hpBarContainer.classList.add('absolute', 'bottom-0', 'left-0', 'w-full', 'h-1.5', 'px-0.5');
                        
                        const hpBar = document.createElement('div');
                        hpBar.classList.add('h-full', 'rounded-sm', 'transition-all', 'duration-300');
                        
                        // 根据HP比例设置颜色
                        const hpPercent = (character.hp / character.maxHp) * 100;
                        if (hpPercent > 70) {
                            hpBar.classList.add('bg-green-500');
                        } else if (hpPercent > 30) {
                            hpBar.classList.add('bg-yellow-500');
                        } else {
                            hpBar.classList.add('bg-red-500');
                        }
                        
                        hpBar.style.width = `${hpPercent}%`;
                        hpBarContainer.appendChild(hpBar);
                        charElement.appendChild(hpBarContainer);
                        
                        cell.appendChild(charElement);
                    }
                    
                    // 如果是选中的格子，添加高亮
                    if (gameState.selectedCell && gameState.selectedCell.x === x && gameState.selectedCell.y === y) {
                        cell.classList.add('bg-blue-100', 'ring-2', 'ring-blue-500');
                    }
                    
                    mapContainer.appendChild(cell);
                }
            }
            
            // 如果有选中的角色，高亮可行动的格子
            if (gameState.selectedCharacter && !gameState.selectedCharacter.moved && gameState.turn === 'player') {
                highlightSelectableCells(gameState.selectedCharacter);
            }
            
            // 更新玩家状态显示
            updatePlayerPartyDisplay();
        }

        // 更新玩家队伍显示
        function updatePlayerPartyDisplay() {
            const container = document.getElementById('player-party');
            container.innerHTML = '';
            
            const players = gameState.characters.filter(char => char.type === CHARACTER_TYPES.PLAYER);
            
            players.forEach(player => {
                const charElement = document.createElement('div');
                charElement.classList.add('character', player.color, 'relative');
                charElement.textContent = player.name;
                charElement.title = `${player.fullName} (等级: ${player.level})
HP: ${player.hp}/${player.maxHp}
攻击: ${player.attack} 防御: ${player.defense}
经验: ${player.experience}/${player.nextLevelExp}`;
                
                // 等级标记
                const levelMarker = document.createElement('div');
                levelMarker.classList.add('absolute', 'top-0', 'left-0', 'text-[8px]', 'bg-black', 'text-white', 'px-1', 'rounded-sm');
                levelMarker.textContent = `Lv${player.level}`;
                charElement.appendChild(levelMarker);
                
                // 添加HP条
                const hpBarContainer = document.createElement('div');
                hpBarContainer.classList.add('absolute', 'bottom-0', 'left-0', 'w-full', 'h-1.5', 'px-0.5');
                
                const hpBar = document.createElement('div');
                hpBar.classList.add('h-full', 'rounded-sm');
                
                // 根据HP比例设置颜色
                const hpPercent = (player.hp / player.maxHp) * 100;
                if (hpPercent > 70) {
                    hpBar.classList.add('bg-green-500');
                } else if (hpPercent > 30) {
                    hpBar.classList.add('bg-yellow-500');
                } else {
                    hpBar.classList.add('bg-red-500');
                }
                
                hpBar.style.width = `${hpPercent}%`;
                hpBarContainer.appendChild(hpBar);
                charElement.appendChild(hpBarContainer);
                
                // 如果已经移动，添加标记
                if (player.moved) {
                    const movedIndicator = document.createElement('div');
                    movedIndicator.classList.add('absolute', 'top-0', 'right-0', 'w-3', 'h-3', 'bg-gray-400', 'rounded-full');
                    charElement.appendChild(movedIndicator);
                }
                
                container.appendChild(charElement);
            });
        }

        // 获取指定位置的角色
        function getCharacterAtPosition(x, y) {
            return gameState.characters.find(char => char.x === x && char.y === y);
        }

        // 添加事件监听器 - 优化操作体验
        function addEventListeners() {
            // 地图格子点击事件
            document.getElementById('game-map').addEventListener('click', handleCellClick);
            
            // 按钮事件
            document.getElementById('move-btn').addEventListener('click', handleMove);
            document.getElementById('attack-btn').addEventListener('click', handleAttack);
            document.getElementById('ability-btn').addEventListener('click', handleAbility);
            document.getElementById('end-turn-btn').addEventListener('click', endPlayerTurn);
            document.getElementById('new-game-btn').addEventListener('click', initGame);
            
            // 添加键盘快捷键
            document.addEventListener('keydown', (e) => {
                if (gameState.turn !== 'player' || gameState.gameOver) return;
                
                switch(e.key.toLowerCase()) {
                    case 'm': // 移动
                        handleMove();
                        e.preventDefault();
                        break;
                    case 'a': // 攻击
                        handleAttack();
                        e.preventDefault();
                        break;
                    case 'e': // 结束回合
                        endPlayerTurn();
                        e.preventDefault();
                        break;
                }
            });
            
            // 鼠标悬停提示
            document.getElementById('game-map').addEventListener('mousemove', handleMouseOver);
            document.getElementById('game-map').addEventListener('mouseout', handleMouseOut);
        }

        // 处理鼠标悬停 - 优化操作体验
        function handleMouseOver(e) {
            const cell = e.target.closest('.grid-cell');
            if (!cell) return;
            
            const x = parseInt(cell.dataset.x);
            const y = parseInt(cell.dataset.y);
            
            // 检查这个格子是否有角色
            const character = getCharacterAtPosition(x, y);
            const mapCell = gameState.map[y][x];
            
            let tooltipText = `坐标: (${x}, ${y})`;
            
            if (character) {
                tooltipText = `${character.fullName}
HP: ${character.hp}/${character.maxHp}
攻击: ${character.attack} 防御: ${character.defense}`;
                
                if (character.abilities && character.abilities.length > 0) {
                    tooltipText += "\n技能:";
                    character.abilities.forEach(ability => {
                        const cooldownText = ability.currentCooldown > 0 ? ` (冷却: ${ability.currentCooldown})` : "";
                        tooltipText += `\n- ${ability.name}: ${ability.description}${cooldownText}`;
                    });
                }
            } else if (mapCell.type === CELL_TYPES.ITEM) {
                let itemName = "";
                switch(mapCell.itemType) {
                    case ITEM_TYPES.POTION: itemName = "治疗药剂"; break;
                    case ITEM_TYPES.WEAPON: itemName = "武器"; break;
                    case ITEM_TYPES.ARMOR: itemName = "防具"; break;
                    case ITEM_TYPES.TREASURE: itemName = "宝藏"; break;
                    case ITEM_TYPES.SCROLL: itemName = "卷轴"; break;
                }
                tooltipText = `${itemName}`;
            } else if (mapCell.type === CELL_TYPES.EVENT) {
                let eventName = "";
                switch(mapCell.eventType) {
                    case EVENT_TYPES.MERCHANT: eventName = "商人"; break;
                    case EVENT_TYPES.SHRINE: eventName = "神社"; break;
                    case EVENT_TYPES.TREASURE_ROOM: eventName = "宝藏室"; break;
                    case EVENT_TYPES.AMBUSH: eventName = "埋伏点"; break;
                    case EVENT_TYPES.TRAINER: eventName = "训练师"; break;
                    default: eventName = "神秘事件";
                }
                tooltipText = `${eventName}`;
            }
            
            // 创建或更新提示框
            let tooltip = document.querySelector('.tooltip');
            if (!tooltip) {
                tooltip = document.createElement('div');
                tooltip.classList.add('tooltip');
                document.body.appendChild(tooltip);
            }
            
            tooltip.innerHTML = tooltipText.replace(/\n/g, '<br>');
            tooltip.style.left = `${e.pageX + 10}px`;
            tooltip.style.top = `${e.pageY + 10}px`;
            tooltip.style.opacity = '1';
        }

        // 处理鼠标离开
        function handleMouseOut(e) {
            const tooltip = document.querySelector('.tooltip');
            if (tooltip) {
                tooltip.style.opacity = '0';
            }
        }

        // 处理格子点击 - 优化操作体验
        function handleCellClick(e) {
            // 如果不是玩家回合或游戏结束，不能操作
            if (gameState.turn !== 'player' || gameState.gameOver) return;
            
            const cell = e.target.closest('.grid-cell');
            if (!cell) return;
            
            const x = parseInt(cell.dataset.x);
            const y = parseInt(cell.dataset.y);
            
            // 播放选择音效
            SoundManager.play('select');
            
            // 检查这个格子是否有角色
            const character = getCharacterAtPosition(x, y);
            
            // 如果点击了有角色的格子
            if (character) {
                // 只能选择己方角色
                if (character.type === CHARACTER_TYPES.PLAYER) {
                    selectCharacter(character, x, y);
                } else {
                    // 选中敌人，尝试攻击
                    if (gameState.selectedCharacter && !gameState.selectedCharacter.moved) {
                        selectCell(x, y);
                        // 自动尝试攻击
                        setTimeout(handleAttack, 300);
                    } else {
                        showInfo(`这是敌人: ${character.fullName} (HP: ${character.hp}/${character.maxHp})`);
                    }
                }
            } 
            // 如果点击了事件格子
            else if (gameState.map[y][x].type === CELL_TYPES.EVENT) {
                if (gameState.selectedCharacter && !gameState.selectedCharacter.moved) {
                    // 检查是否在移动范围内
                    const distance = Math.max(Math.abs(x - gameState.selectedCharacter.x), Math.abs(y - gameState.selectedCharacter.y));
                    if (distance <= 2) {
                        selectCell(x, y);
                        // 先移动到事件格子，再触发事件
                        const oldX = gameState.selectedCharacter.x;
                        const oldY = gameState.selectedCharacter.y;
                        
                        // 如果不在同一个格子，先移动
                        if (oldX !== x || oldY !== y) {
                            gameState.selectedCharacter.x = x;
                            gameState.selectedCharacter.y = y;
                            gameState.selectedCharacter.moved = true;
                            
                            logMessage(`${gameState.selectedCharacter.fullName}移动到了事件点`);
                            SoundManager.play('move');
                            
                            renderMap();
                            
                            // 移动后触发事件
                            setTimeout(() => {
                                triggerEvent(x, y);
                            }, 500);
                        } else {
                            // 已经在事件格子上，直接触发
                            triggerEvent(x, y);
                        }
                    } else {
                        showInfo('距离太远，无法到达事件点');
                    }
                } else {
                    showInfo('请先选择一个未行动的己方武将');
                }
            }
            // 如果已经选中了角色，点击空格子
            else if (gameState.selectedCharacter && gameState.map[y][x].type !== CELL_TYPES.OBSTACLE) {
                selectCell(x, y);
                
                // 如果是物品格子，自动尝试移动过去
                if (gameState.map[y][x].type === CELL_TYPES.ITEM) {
                    setTimeout(handleMove, 300);
                }
            }
        }

        // 选择角色 - 优化操作体验
        function selectCharacter(character, x, y) {
            // 如果角色已经移动过，不能再操作
            if (character.moved) {
                showInfo(`${character.fullName}已经移动过了`);
                return;
            }
            
            gameState.selectedCharacter = character;
            gameState.selectedCell = {x, y};
            
            // 更新UI
            renderMap(); // 重新渲染以显示可行动格子
            
            // 显示角色详细信息
            let abilityText = "";
            if (character.abilities && character.abilities.length > 0) {
                abilityText = "<br>技能:";
                character.abilities.forEach(ability => {
                    const cooldownText = ability.currentCooldown > 0 ? ` (冷却: ${ability.currentCooldown})` : "";
                    abilityText += `<br>- ${ability.name}: ${ability.description}${cooldownText}`;
                });
            }
            
            showInfo(`<strong>${character.fullName}</strong> (等级: ${character.level})<br>
HP: ${character.hp}/${character.maxHp}<br>
攻击: ${character.attack} 防御: ${character.defense}<br>
经验: ${character.experience}/${character.nextLevelExp}${abilityText}`);
            
            // 高亮选中的角色
            const charElement = document.querySelector(`.character[data-id="${character.id}"]`);
            if (charElement) {
                charElement.classList.add('character-selected');
            }
        }

        // 选择格子 - 优化操作体验
        function selectCell(x, y) {
            gameState.selectedCell = {x, y};
            
            // 重新渲染地图以显示选中状态
            renderMap();
            
            // 检查是否是敌人
            const enemy = getCharacterAtPosition(x, y);
            if (enemy && enemy.type === CHARACTER_TYPES.ENEMY) {
                showInfo(`敌人: ${enemy.fullName} (HP: ${enemy.hp}/${enemy.maxHp})<br>攻击: ${enemy.attack} 防御: ${enemy.defense}`);
            } else {
                // 检查是否是物品
                const cell = gameState.map[y][x];
                if (cell.type === CELL_TYPES.ITEM) {
                    let itemName = "";
                    switch(cell.itemType) {
                        case ITEM_TYPES.POTION: itemName = "治疗药剂"; break;
                        case ITEM_TYPES.WEAPON: itemName = "武器"; break;
                        case ITEM_TYPES.ARMOR: itemName = "防具"; break;
                        case ITEM_TYPES.TREASURE: itemName = "宝藏"; break;
                        case ITEM_TYPES.SCROLL: itemName = "卷轴"; break;
                    }
                    showInfo(`物品: ${itemName} (${x}, ${y})`);
                } else if (cell.type === CELL_TYPES.EVENT) {
                    let eventName = "";
                    switch(cell.eventType) {
                        case EVENT_TYPES.MERCHANT: eventName = "商人"; break;
                        case EVENT_TYPES.SHRINE: eventName = "神社"; break;
                        case EVENT_TYPES.TREASURE_ROOM: eventName = "宝藏室"; break;
                        case EVENT_TYPES.AMBUSH: eventName = "埋伏点"; break;
                        case EVENT_TYPES.TRAINER: eventName = "训练师"; break;
                        default: eventName = "神秘事件";
                    }
                    showInfo(`事件: ${eventName} (${x}, ${y})`);
                } else {
                    showInfo(`选中了格子 (${x}, ${y})`);
                }
            }
        }

        // 高亮可移动的格子 - 优化操作体验
        function highlightSelectableCells(character) {
            // 计算可移动范围（2格范围内）
            for (let dy = -2; dy <= 2; dy++) {
                for (let dx = -2; dx <= 2; dx++) {
                    // 不能原地不动
                    if (dx === 0 && dy === 0) continue;
                    
                    const x = character.x + dx;
                    const y = character.y + dy;
                    
                    // 检查是否在地图范围内
                    if (x >= 0 && x < GAME_CONFIG.mapSize && y >= 0 && y < GAME_CONFIG.mapSize) {
                        // 检查是否是障碍物
                        if (gameState.map[y][x].type !== CELL_TYPES.OBSTACLE) {
                            // 检查是否有其他角色
                            const targetChar = getCharacterAtPosition(x, y);
                            if (!targetChar) {
                                // 可移动的格子
                                const cell = document.querySelector(`.grid-cell[data-x="${x}"][data-y="${y}"]`);
                                if (cell) {
                                    cell.classList.add('grid-cell-move');
                                    
                                    // 添加移动提示
                                    if (!cell.querySelector('.move-indicator')) {
                                        const indicator = document.createElement('div');
                                        indicator.classList.add('move-indicator', 'text-xs', 'text-blue-600', 'opacity-70', 'absolute');
                                        indicator.textContent = '移动';
                                        cell.appendChild(indicator);
                                    }
                                }
                            } else if (targetChar.type === CHARACTER_TYPES.ENEMY) {
                                // 可攻击的敌人
                                const cell = document.querySelector(`.grid-cell[data-x="${x}"][data-y="${y}"]`);
                                const distance = Math.max(Math.abs(x - character.x), Math.abs(y - character.y));
                                if (distance <= 1 && cell) {
                                    cell.classList.add('grid-cell-attack');
                                    
                                    // 添加攻击提示
                                    if (!cell.querySelector('.attack-indicator')) {
                                        const indicator = document.createElement('div');
                                        indicator.classList.add('attack-indicator', 'text-xs', 'text-red-600', 'opacity-70', 'absolute');
                                        indicator.textContent = '攻击';
                                        cell.appendChild(indicator);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 处理移动 - 优化操作体验
        function handleMove() {
            if (!gameState.selectedCharacter || !gameState.selectedCell) {
                showInfo('请先选择一个角色和目标位置');
                return;
            }
            
            const {x, y} = gameState.selectedCell;
            const character = gameState.selectedCharacter;
            
            // 检查角色是否已经移动
            if (character.moved) {
                showInfo(`${character.fullName}已经移动过了`);
                return;
            }
            
            // 检查目标位置是否有敌人
            const targetChar = getCharacterAtPosition(x, y);
            if (targetChar && targetChar.type === CHARACTER_TYPES.ENEMY) {
                showInfo('目标位置有敌人，不能移动过去，请选择攻击');
                return;
            }
            
            // 检查是否是障碍物
            if (gameState.map[y][x].type === CELL_TYPES.OBSTACLE) {
                showInfo('目标位置是障碍物，不能移动过去');
                return;
            }
            
            // 检查是否在移动范围内（简单距离检查）
            const distance = Math.max(Math.abs(x - character.x), Math.abs(y - character.y));
            if (distance > 2) {
                showInfo('距离太远，不能移动过去');
                return;
            }
            
            // 播放移动音效
            SoundManager.play('move');
            
            // 执行移动
            const oldX = character.x;
            const oldY = character.y;
            character.x = x;
            character.y = y;
            character.moved = true;
            
            // 更新关卡进度
            updateLevelProgress();
            
            // 检查是否有物品
            const cell = gameState.map[y][x];
            if (cell.type === CELL_TYPES.ITEM) {
                collectItem(character, cell);
                cell.type = CELL_TYPES.EMPTY; // 移除物品
            }
            
            logMessage(`${character.fullName}移动到了(${x}, ${y})`);
            
            // 先更新角色位置并添加移动动画
            const charElement = document.querySelector(`.character[data-id="${character.id}"]`);
            if (charElement) {
                charElement.classList.add('character-moving');
                
                // 动画结束后重新渲染地图
                setTimeout(() => {
                    renderMap();
                }, 300);
            } else {
                renderMap();
            }
        }

        // 处理攻击 - 优化操作体验
        function handleAttack() {
            if (!gameState.selectedCharacter || !gameState.selectedCell) {
                showInfo('请先选择一个角色和目标敌人');
                return;
            }
            
            const {x, y} = gameState.selectedCell;
            const attacker = gameState.selectedCharacter;
            const defender = getCharacterAtPosition(x, y);
            
            // 检查角色是否已经移动
            if (attacker.moved) {
                showInfo(`${attacker.fullName}已经行动过了`);
                return;
            }
            
            // 检查目标是否是敌人
            if (!defender || defender.type !== CHARACTER_TYPES.ENEMY) {
                showInfo('目标位置没有敌人');
                return;
            }
            
            // 检查距离是否可以攻击（相邻格子）
            const distance = Math.max(Math.abs(x - attacker.x), Math.abs(y - attacker.y));
            if (distance > 1) {
                showInfo('距离太远，不能攻击');
                return;
            }
            
            // 播放攻击音效
            SoundManager.play('attack');
            
            // 计算伤害，考虑防御
            let damage = Math.max(1, attacker.attack - Math.floor(defender.defense / 3) - Math.floor(Math.random() * 3));
            
            // 检查是否有技能影响
            if (defender.fullName === '典韦' && defender.abilities[1] && defender.abilities[1].name === '狂怒') {
                const hpPercent = defender.hp / defender.maxHp;
                const rageBonus = Math.max(0, Math.floor((1 - hpPercent) * 10));
                damage = Math.max(1, damage - rageBonus);
                logMessage(`${defender.fullName}因狂怒减少了${rageBonus}点伤害！`);
            }
            
            defender.hp -= damage;
            
            // 显示伤害数字
            showDamageIndicator(x, y, damage);
            
            // 添加受伤动画
            const defenderElement = document.querySelector(`.character[data-id="${defender.id}"]`);
            if (defenderElement) {
                defenderElement.classList.add('character-hurt');
            }
            
            logMessage(`${attacker.fullName}攻击了${defender.fullName}，造成${damage}点伤害!`);
            
            // 曹操的奸雄技能：攻击后恢复自身造成伤害的30%
            if (attacker.fullName === '曹操' && attacker.abilities[0] && attacker.abilities[0].name === '奸雄') {
                const healAmount = Math.floor(damage * 0.3);
                attacker.hp = Math.min(attacker.maxHp, attacker.hp + healAmount);
                showHealIndicator(attacker.x, attacker.y, healAmount);
                logMessage(`${attacker.fullName}触发了奸雄技能，恢复了${healAmount}点生命值！`);
                SoundManager.play('heal');
            }
            
            // 播放被击中音效
            SoundManager.play('hit');
            
            // 检查敌人是否被击败
            if (defender.hp <= 0) {
                // 添加死亡动画
                if (defenderElement) {
                    defenderElement.classList.add('character-dying');
                }
                
                logMessage(`${defender.fullName}被击败了!`);
                
                // 玩家获得经验值
                const expGained = 50 + (defender.isElite ? 30 : 0) + Math.floor(gameState.level * 10);
                attacker.experience += expGained;
                logMessage(`${attacker.fullName}获得了${expGained}点经验值！`);
                
                // 检查是否升级
                checkLevelUp(attacker);
                
                // 从角色列表中移除
                setTimeout(() => {
                    gameState.characters = gameState.characters.filter(char => char.id !== defender.id);
                    
                    // 更新关卡进度
                    updateLevelProgress();
                    
                    // 检查是否所有敌人都被击败
                    checkVictory();
                    
                    renderMap();
                }, 1000);
            }
            
            attacker.moved = true; // 攻击后不能再移动
            
            // 更新技能冷却
            updateAbilityCooldowns();
            
            // 动画结束后重新渲染地图
            if (defender.hp > 0) {
                setTimeout(() => {
                    renderMap();
                }, 500);
            }
        }

        // 处理技能
        function handleAbility() {
            if (!gameState.selectedCharacter || gameState.selectedCharacter.type !== CHARACTER_TYPES.PLAYER) {
                showInfo('请先选择一个己方武将');
                return;
            }
            
            const character = gameState.selectedCharacter;
            
            // 检查角色是否已经移动
            if (character.moved) {
                showInfo(`${character.fullName}已经行动过了`);
                return;
            }
            
            // 检查是否有可用技能
            const availableAbilities = character.abilities.filter(ability => ability.currentCooldown === 0);
            
            if (availableAbilities.length === 0) {
                showInfo(`${character.fullName}没有可用技能（技能正在冷却中）`);
                return;
                return;
            }
            
            // 显示技能选择弹窗
            showEventPopup(
                `${character.fullName}的技能`,
                '选择要使用的技能:',
                availableAbilities.map(ability => ({
                    text: `${ability.name} - ${ability.description}`,
                    action: () => useAbility(character, ability)
                }))
            );
        }

        // 使用技能
        function useAbility(character, ability) {
            // 关闭弹窗
            hideEventPopup();
            
            // 播放技能音效
            SoundManager.play('attack');
            
            // 根据不同技能执行不同效果
            switch(character.fullName) {
                case '刘备':
                    if (ability.name === '仁德') {
                        // 恢复周围友军10点生命值
                        let healed = false;
                        for (let dy = -1; dy <= 1; dy++) {
                            for (let dx = -1; dx <= 1; dx++) {
                                const x = character.x + dx;
                                const y = character.y + dy;
                                
                                const ally = getCharacterAtPosition(x, y);
                                if (ally && ally.type === CHARACTER_TYPES.PLAYER) {
                                    ally.hp = Math.min(ally.maxHp, ally.hp + 10);
                                    showHealIndicator(x, y, 10);
                                    healed = true;
                                }
                            }
                        }
                        
                        if (healed) {
                            logMessage(`${character.fullName}使用了仁德技能，恢复了友军的生命值！`);
                        } else {
                            logMessage(`${character.fullName}使用了仁德技能，但周围没有友军！`);
                        }
                    } else if (ability.name === '义勇') {
                        // 提升自身和相邻友军的防御力2回合
                        for (let dy = -1; dy <= 1; dy++) {
                            for (let dx = -1; dx <= 1; dx++) {
                                const x = character.x + dx;
                                const y = character.y + dy;
                                
                                const ally = getCharacterAtPosition(x, y);
                                if (ally && ally.type === CHARACTER_TYPES.PLAYER) {
                                    ally.temporaryDefense = (ally.temporaryDefense || 0) + 3;
                                    ally.temporaryDefenseDuration = 2;
                                }
                            }
                        }
                        logMessage(`${character.fullName}使用了义勇技能，提升了友军的防御力！`);
                    }
                    break;
                    
                case '关羽':
                    if (ability.name === '青龙斩') {
                        // 对单个敌人造成150%伤害
                        if (gameState.selectedCell) {
                            const defender = getCharacterAtPosition(gameState.selectedCell.x, gameState.selectedCell.y);
                            if (defender && defender.type === CHARACTER_TYPES.ENEMY) {
                                const distance = Math.max(
                                    Math.abs(gameState.selectedCell.x - character.x), 
                                    Math.abs(gameState.selectedCell.y - character.y)
                                );
                                
                                if (distance <= 1) {
                                    const damage = Math.floor(character.attack * 1.5 - Math.floor(defender.defense / 3));
                                    defender.hp -= damage;
                                    showDamageIndicator(gameState.selectedCell.x, gameState.selectedCell.y, damage);
                                    
                                    logMessage(`${character.fullName}使用了青龙斩，对${defender.fullName}造成了${damage}点伤害！`);
                                    
                                    // 受伤动画
                                    const defenderElement = document.querySelector(`.character[data-id="${defender.id}"]`);
                                    if (defenderElement) {
                                        defenderElement.classList.add('character-hurt');
                                    }
                                    
                                    // 检查敌人是否被击败
                                    if (defender.hp <= 0) {
                                        if (defenderElement) {
                                            defenderElement.classList.add('character-dying');
                                        }
                                        
                                        logMessage(`${defender.fullName}被击败了!`);
                                        
                                        // 玩家获得经验值
                                        const expGained = 50 + (defender.isElite ? 30 : 0) + Math.floor(gameState.level * 10);
                                        character.experience += expGained;
                                        logMessage(`${character.fullName}获得了${expGained}点经验值！`);
                                        
                                        // 检查是否升级
                                        checkLevelUp(character);
                                        
                                        // 延迟移除死亡单位
                                        setTimeout(() => {
                                            gameState.characters = gameState.characters.filter(char => char.id !== defender.id);
                                            updateLevelProgress();
                                            checkVictory();
                                            renderMap();
                                        }, 1000);
                                    }
                                } else {
                                    logMessage('目标距离太远，无法使用青龙斩！');
                                }
                            } else {
                                logMessage('请先选择一个敌人目标！');
                            }
                        } else {
                            logMessage('请先选择一个敌人目标！');
                        }
                    }
                    break;
                    
                case '张飞':
                    if (ability.name === '咆哮') {
                        // 对周围所有敌人造成少量伤害并震慑他们
                        let enemiesHit = 0;
                        for (let dy = -1; dy <= 1; dy++) {
                            for (let dx = -1; dx <= 1; dx++) {
                                if (dx === 0 && dy === 0) continue; // 跳过自己
                                
                                const x = character.x + dx;
                                const y = character.y + dy;
                                
                                const enemy = getCharacterAtPosition(x, y);
                                if (enemy && enemy.type === CHARACTER_TYPES.ENEMY) {
                                    const damage = Math.max(1, Math.floor(character.attack * 0.7 - Math.floor(enemy.defense / 3)));
                                    enemy.hp -= damage;
                                    enemy.stunned = true; // 震慑效果
                                    showDamageIndicator(x, y, damage);
                                    enemiesHit++;
                                    
                                    // 受伤动画
                                    const enemyElement = document.querySelector(`.character[data-id="${enemy.id}"]`);
                                    if (enemyElement) {
                                        enemyElement.classList.add('character-hurt');
                                    }
                                }
                            }
                        }
                        
                        if (enemiesHit > 0) {
                            logMessage(`${character.fullName}使用了咆哮，对${enemiesHit}个敌人造成了伤害并震慑了他们！`);
                        } else {
                            logMessage(`${character.fullName}使用了咆哮，但周围没有敌人！`);
                        }
                    }
                    break;
            }
            
            // 设置技能冷却
            ability.currentCooldown = ability.cooldown;
            
            // 使用技能后不能再行动
            character.moved = true;
            
            // 重新渲染
            setTimeout(() => {
                renderMap();
            }, 500);
        }

        // 显示伤害数字
        function showDamageIndicator(x, y, value) {
            const mapContainer = document.getElementById('game-map');
            const indicator = document.createElement('div');
            indicator.classList.add('damage-indicator');
            indicator.textContent = value;
            
            // 计算位置
            const cellSize = 56; // 格子大小(px)
            indicator.style.left = `${x * cellSize + cellSize/2}px`;
            indicator.style.top = `${y * cellSize}px`;
            
            mapContainer.appendChild(indicator);
            
            // 动画结束后移除元素
            setTimeout(() => {
                indicator.remove();
            }, 1000);
        }

        // 显示治疗数字
        function showHealIndicator(x, y, value) {
            const mapContainer = document.getElementById('game-map');
            const indicator = document.createElement('div');
            indicator.classList.add('heal-indicator');
            indicator.textContent = `+${value}`;
            
            // 计算位置
            const cellSize = 56; // 格子大小(px)
            indicator.style.left = `${x * cellSize + cellSize/2}px`;
            indicator.style.top = `${y * cellSize}px`;
            
            mapContainer.appendChild(indicator);
            
            // 动画结束后移除元素
            setTimeout(() => {
                indicator.remove();
            }, 1000);
        }

        // 收集物品 - 增强Roguelike元素
        function collectItem(character, cell) {
            SoundManager.play('item');
            
            switch(cell.itemType) {
                case ITEM_TYPES.POTION:
                    const healAmount = 30 + Math.floor(Math.random() * 20) + Math.floor(character.level * 5);
                    character.hp = Math.min(character.maxHp, character.hp + healAmount);
                    logMessage(`${character.fullName}找到了治疗药剂，恢复了${healAmount}点生命值!`);
                    
                    // 显示治疗数字
                    showHealIndicator(character.x, character.y, healAmount);
                    
                    showNotification(`${character.fullName}恢复了${healAmount}点生命值!`);
                    break;
                    
                case ITEM_TYPES.WEAPON:
                    const attackBoost = 5 + Math.floor(Math.random() * 5) + Math.floor(character.level * 2);
                    character.attack += attackBoost;
                    logMessage(`${character.fullName}找到了精良武器，攻击力提升了${attackBoost}点!`);
                    
                    showNotification(`${character.fullName}攻击力提升${attackBoost}点!`);
                    break;
                    
                case ITEM_TYPES.ARMOR:
                    const defenseBoost = 3 + Math.floor(Math.random() * 3) + Math.floor(character.level * 1);
                    character.defense += defenseBoost;
                    logMessage(`${character.fullName}找到了坚固防具，防御力提升了${defenseBoost}点!`);
                    
                    showNotification(`${character.fullName}防御力提升${defenseBoost}点!`);
                    break;
                    
                case ITEM_TYPES.TREASURE:
                    const expBoost = 50 + Math.floor(Math.random() * 50) + Math.floor(character.level * 10);
                    character.experience += expBoost;
                    logMessage(`${character.fullName}找到了宝藏，获得了${expBoost}点经验值!`);
                    
                    // 检查是否升级
                    checkLevelUp(character);
                    
                    showNotification(`${character.fullName}获得了${expBoost}点经验值!`);
                    break;
                    
                case ITEM_TYPES.SCROLL:
                    // 随机重置一个技能的冷却
                    if (character.abilities && character.abilities.length > 0) {
                        const ability = character.abilities[Math.floor(Math.random() * character.abilities.length)];
                        if (ability.currentCooldown > 0) {
                            const oldCooldown = ability.currentCooldown;
                            ability.currentCooldown = 0;
                            logMessage(`${character.fullName}使用了魔法卷轴，${ability.name}的冷却已重置!`);
                            showNotification(`${ability.name}的冷却已重置!`);
                        } else {
                            // 如果所有技能都没有冷却，就提升一个随机属性
                            const boostType = Math.random() > 0.5 ? 'attack' : 'defense';
                            const boostAmount = 2 + Math.floor(Math.random() * 3);
                            character[boostType] += boostAmount;
                            logMessage(`${character.fullName}使用了魔法卷轴，${boostType === 'attack' ? '攻击力' : '防御力'}提升了${boostAmount}点!`);
                            showNotification(`${character.fullName}${boostType === 'attack' ? '攻击力' : '防御力'}提升${boostAmount}点!`);
                        }
                    }
                    break;
            }
        }

        // 触发事件 - 增强Roguelike元素
        function triggerEvent(x, y) {
            const cell = gameState.map[y][x];
            SoundManager.play('event');
            
            // 触发事件后移除事件点
            const eventType = cell.eventType;
            cell.type = CELL_TYPES.EMPTY;
            
            switch(eventType) {
                case EVENT_TYPES.MERCHANT:
                    // 商人：可以购买物品
                    const itemsForSale = [
                        {name: '治疗药剂', effect: () => {
                            const healAmount = 50;
                            gameState.selectedCharacter.hp = Math.min(gameState.selectedCharacter.maxHp, gameState.selectedCharacter.hp + healAmount);
                            logMessage(`${gameState.selectedCharacter.fullName}购买了治疗药剂，恢复了${healAmount}点生命值!`);
                            showHealIndicator(x, y, healAmount);
                        }},
                        {name: '锋利的剑', effect: () => {
                            const attackBoost = 8;
                            gameState.selectedCharacter.attack += attackBoost;
                            logMessage(`${gameState.selectedCharacter.fullName}购买了锋利的剑，攻击力提升了${attackBoost}点!`);
                        }},
                        {name: '坚固的盾', effect: () => {
                            const defenseBoost = 5;
                            gameState.selectedCharacter.defense += defenseBoost;
                            logMessage(`${gameState.selectedCharacter.fullName}购买了坚固的盾，防御力提升了${defenseBoost}点!`);
                        }}
                    ];
                    
                    showEventPopup(
                        '遇到商人',
                        '商人正在出售一些物品，你想要购买什么？',
                        [...itemsForSale.map(item => ({
                            text: item.name,
                            action: () => {
                                item.effect();
                                hideEventPopup();
                                renderMap();
                            }
                        })),
                        {text: '不买了', action: hideEventPopup}
                        ]
                    );
                    break;
                    
                case EVENT_TYPES.SHRINE:
                    // 神社：随机获得祝福或诅咒
                    const isBlessed = Math.random() > 0.3; // 70%概率获得祝福
                    
                    if (isBlessed) {
                        const blessings = [
                            () => {
                                const healAmount = Math.floor(gameState.selectedCharacter.maxHp * 0.5);
                                gameState.selectedCharacter.hp = Math.min(gameState.selectedCharacter.maxHp, gameState.selectedCharacter.hp + healAmount);
                                logMessage(`${gameState.selectedCharacter.fullName}受到了神社的祝福，恢复了${healAmount}点生命值!`);
                                showHealIndicator(x, y, healAmount);
                            },
                            () => {
                                const attackBoost = 5;
                                gameState.selectedCharacter.attack += attackBoost;
                                logMessage(`${gameState.selectedCharacter.fullName}受到了神社的祝福，攻击力永久提升了${attackBoost}点!`);
                            },
                            () => {
                                // 重置所有技能冷却
                                gameState.selectedCharacter.abilities.forEach(ability => {
                                    ability.currentCooldown = 0;
                                });
                                logMessage(`${gameState.selectedCharacter.fullName}受到了神社的祝福，所有技能冷却已重置!`);
                            }
                        ];
                        
                        const randomBlessing = blessings[Math.floor(Math.random() * blessings.length)];
                        randomBlessing();
                        
                        showEventPopup(
                            '神社的祝福',
                            '你在神社祈祷，获得了神灵的祝福！',
                            [{text: '感谢神灵', action: hideEventPopup}]
                        );
                    } else {
                        const curses = [
                            () => {
                                const damage = Math.floor(gameState.selectedCharacter.maxHp * 0.2);
                                gameState.selectedCharacter.hp = Math.max(1, gameState.selectedCharacter.hp - damage);
                                logMessage(`${gameState.selectedCharacter.fullName}受到了诅咒，损失了${damage}点生命值!`);
                                showDamageIndicator(x, y, damage);
                            },
                            () => {
                                const attackReduction = 3;
                                gameState.selectedCharacter.attack = Math.max(1, gameState.selectedCharacter.attack - attackReduction);
                                logMessage(`${gameState.selectedCharacter.fullName}受到了诅咒，攻击力降低了${attackReduction}点!`);
                            }
                        ];
                        
                        const randomCurse = curses[Math.floor(Math.random() * curses.length)];
                        randomCurse();
                        
                        showEventPopup(
                            '不幸的诅咒',
                            '你触怒了神灵，受到了诅咒！',
                            [{text: '真倒霉', action: hideEventPopup}]
                        );
                    }
                    break;
                    
                case EVENT_TYPES.TREASURE_ROOM:
                    // 宝藏室：获得随机奖励
                    const rewards = [
                        () => {
                            const healAmount = 100;
                            gameState.selectedCharacter.hp = Math.min(gameState.selectedCharacter.maxHp, gameState.selectedCharacter.hp + healAmount);
                            logMessage(`${gameState.selectedCharacter.fullName}找到了满箱的药剂，恢复了${healAmount}点生命值!`);
                            showHealIndicator(x, y, healAmount);
                        },
                        () => {
                            const expBoost = 200;
                            gameState.selectedCharacter.experience += expBoost;
                            logMessage(`${gameState.selectedCharacter.fullName}找到了古代秘籍，获得了${expBoost}点经验值!`);
                            checkLevelUp(gameState.selectedCharacter);
                        },
                        () => {
                            const attackBoost = 10;
                            const defenseBoost = 5;
                            gameState.selectedCharacter.attack += attackBoost;
                            gameState.selectedCharacter.defense += defenseBoost;
                            logMessage(`${gameState.selectedCharacter.fullName}找到了神兵利器，攻击力提升${attackBoost}点，防御力提升${defenseBoost}点!`);
                        }
                    ];
                    
                    const randomReward = rewards[Math.floor(Math.random() * rewards.length)];
                    randomReward();
                    
                    showEventPopup(
                        '发现宝藏室',
                        '你找到了一个隐藏的宝藏室！',
                        [{text: '带走宝藏', action: hideEventPopup}]
                    );
                    break;
                    
                case EVENT_TYPES.AMBUSH:
                    // 埋伏：突然遭遇敌人
                    showEventPopup(
                        '遭遇埋伏！',
                        '你走进了敌人的埋伏圈！',
                        [{text: '准备战斗', action: () => {
                            hideEventPopup();
                            
                            // 生成埋伏的敌人
                            const ambushEnemyCount = 2 + Math.floor(Math.random() * 2);
                            for (let i = 0; i < ambushEnemyCount; i++) {
                                // 寻找周围的空位生成敌人
                                let spawned = false;
                                for (let dy = -2; dy <= 2 && !spawned; dy++) {
                                    for (let dx = -2; dx <= 2 && !spawned; dx++) {
                                        if (dx === 0 && dy === 0) continue;
                                        
                                        const nx = x + dx;
                                        const ny = y + dy;
                                        
                                        if (nx >= 0 && nx < GAME_CONFIG.mapSize && ny >= 0 && ny < GAME_CONFIG.mapSize) {
                                            if (gameState.map[ny][nx].type !== CELL_TYPES.OBSTACLE && !getCharacterAtPosition(nx, ny)) {
                                                // 生成埋伏的敌人
                                                gameState.characters.push({
                                                    id: `ambush-enemy-${Date.now()}-${i}`,
                                                    type: CHARACTER_TYPES.ENEMY,
                                                    name: '伏',
                                                    fullName: '伏兵',
                                                    color: 'bg-red-500',
                                                    x: nx,
                                                    y: ny,
                                                    hp: 50 + Math.floor(gameState.level * 5),
                                                    maxHp: 50 + Math.floor(gameState.level * 5),
                                                    attack: 8 + Math.floor(gameState.level * 2),
                                                    defense: 3 + Math.floor(gameState.level * 1)
                                                });
                                                
                                                spawned = true;
                                            }
                                        }
                                    }
                                }
                            }
                            
                            logMessage('遭遇了敌人的埋伏！');
                            updateGameInfo();
                            renderMap();
                        }}]
                    );
                    break;
                    
                case EVENT_TYPES.TRAINER:
                    // 训练师：可以选择提升一项属性
                    showEventPopup(
                        '遇到训练师',
                        '一位老将军愿意指导你，你想提升什么？',
                        [
                            {text: '提升攻击力', action: () => {
                                const boost = 5 + Math.floor(gameState.selectedCharacter.level * 2);
                                gameState.selectedCharacter.attack += boost;
                                logMessage(`${gameState.selectedCharacter.fullName}接受了训练，攻击力提升了${boost}点!`);
                                hideEventPopup();
                                renderMap();
                            }},
                            {text: '提升防御力', action: () => {
                                const boost = 3 + Math.floor(gameState.selectedCharacter.level * 1);
                                gameState.selectedCharacter.defense += boost;
                                logMessage(`${gameState.selectedCharacter.fullName}接受了训练，防御力提升了${boost}点!`);
                                hideEventPopup();
                                renderMap();
                            }},
                            {text: '提升生命值', action: () => {
                                const boost = 30 + Math.floor(gameState.selectedCharacter.level * 10);
                                gameState.selectedCharacter.maxHp += boost;
                                gameState.selectedCharacter.hp += boost;
                                logMessage(`${gameState.selectedCharacter.fullName}接受了训练，生命值提升了${boost}点!`);
                                showHealIndicator(x, y, boost);
                                hideEventPopup();
                                renderMap();
                            }}
                        ]
                    );
                    break;
                    
                case EVENT_TYPES.MYSTERY:
                    // 神秘事件：随机发生一件事
                    const mysteryEvents = [
                        {
                            title: '神秘老人',
                            description: '一位神秘老人给了你一件礼物',
                            action: () => {
                                const healAmount = 50 + Math.floor(Math.random() * 50);
                                gameState.selectedCharacter.hp = Math.min(gameState.selectedCharacter.maxHp, gameState.selectedCharacter.hp + healAmount);
                                logMessage(`${gameState.selectedCharacter.fullName}从神秘老人那里得到了治疗，恢复了${healAmount}点生命值!`);
                                showHealIndicator(x, y, healAmount);
                            }
                        },
                        {
                            title: '时空裂隙',
                            description: '你被卷入了时空裂隙',
                            action: () => {
                                // 随机传送到地图上的某个位置
                                let newX, newY;
                                do {
                                    newX = Math.floor(Math.random() * GAME_CONFIG.mapSize);
                                    newY = Math.floor(Math.random() * GAME_CONFIG.mapSize);
                                } while (
                                    gameState.map[newY][newX].type === CELL_TYPES.OBSTACLE || 
                                    getCharacterAtPosition(newX, newY)
                                );
                                
                                gameState.selectedCharacter.x = newX;
                                gameState.selectedCharacter.y = newY;
                                logMessage(`${gameState.selectedCharacter.fullName}被传送到了(${newX}, ${newY})!`);
                            }
                        },
                        {
                            title: '古代祭坛',
                            description: '你激活了一个古代祭坛',
                            action: () => {
                                // 随机提升一个属性，降低另一个属性
                                const boostAttack = Math.random() > 0.5;
                                
                                if (boostAttack) {
                                    gameState.selectedCharacter.attack += 8;
                                    gameState.selectedCharacter.defense = Math.max(1, gameState.selectedCharacter.defense - 3);
                                    logMessage(`${gameState.selectedCharacter.fullName}获得了攻击力提升，但防御力下降了!`);
                                } else {
                                    gameState.selectedCharacter.defense += 5;
                                    gameState.selectedCharacter.attack = Math.max(1, gameState.selectedCharacter.attack - 2);
                                    logMessage(`${gameState.selectedCharacter.fullName}获得了防御力提升，但攻击力下降了!`);
                                }
                            }
                        }
                    ];
                    
                    const randomEvent = mysteryEvents[Math.floor(Math.random() * mysteryEvents.length)];
                    randomEvent.action();
                    
                    showEventPopup(
                        randomEvent.title,
                        randomEvent.description,
                        [{text: '继续前进', action: hideEventPopup}]
                    );
                    break;
            }
        }

        // 显示事件弹窗
        function showEventPopup(title, description, choices) {
            document.getElementById('event-title').textContent = title;
            document.getElementById('event-description').textContent = description;
            
            const choicesContainer = document.getElementById('event-choices');
            choicesContainer.innerHTML = '';
            
            choices.forEach(choice => {
                const button = document.createElement('button');
                button.className = 'btn-game w-full justify-center';
                button.textContent = choice.text;
                button.addEventListener('click', choice.action);
                choicesContainer.appendChild(button);
            });
            
            document.getElementById('event-overlay').classList.remove('hidden');
            document.getElementById('event-popup').classList.remove('hidden');
        }

        // 隐藏事件弹窗
        function hideEventPopup() {
            document.getElementById('event-overlay').classList.add('hidden');
            document.getElementById('event-popup').classList.add('hidden');
        }

        // 检查升级
        function checkLevelUp(character) {
            while (character.experience >= character.nextLevelExp) {
                // 升级
                character.level++;
                character.experience -= character.nextLevelExp;
                character.nextLevelExp = Math.floor(character.nextLevelExp * 1.5);
                
                // 提升属性
                const hpBoost = 20 + Math.floor(Math.random() * 10);
                const attackBoost = 3 + Math.floor(Math.random() * 2);
                const defenseBoost = 2 + Math.floor(Math.random() * 1);
                
                character.maxHp += hpBoost;
                character.hp += hpBoost;
                character.attack += attackBoost;
                character.defense += defenseBoost;
                
                logMessage(`${character.fullName}升级了！现在是${character.level}级，属性得到了提升！`);
                showNotification(`${character.fullName}升级到${character.level}级！`);
                SoundManager.play('levelup');
                
                // 每3级可以选择一个 perk
                if (character.level % 3 === 0) {
                    showPerkSelection(character);
                }
            }
        }

        // 显示 perk 选择
        function showPerkSelection(character) {
            const perks = [
                {
                    name: '武器专精',
                    description: '攻击力永久提升5点',
                    effect: (char) => char.attack += 5
                },
                {
                    name: '防具专精',
                    description: '防御力永久提升3点',
                    effect: (char) => char.defense += 3
                },
                {
                    name: '体格强健',
                    description: '最大生命值提升50点',
                    effect: (char) => {
                        char.maxHp += 50;
                        char.hp += 50;
                    }
                },
                {
                    name: '战斗技巧',
                    description: '技能冷却时间减少1回合',
                    effect: (char) => {
                        char.abilities.forEach(ability => {
                            if (ability.cooldown > 1) ability.cooldown--;
                        });
                    }
                },
                {
                    name: '快速恢复',
                    description: '每回合结束时恢复5点生命值',
                    effect: (char) => {
                        char.regeneration = 5;
                    }
                }
            ];
            
            // 随机选择3个perk
            const shuffledPerks = [...perks].sort(() => 0.5 - Math.random());
            const selectedPerks = shuffledPerks.slice(0, 3);
            
            showEventPopup(
                '选择成长方向',
                `恭喜${character.fullName}达到${character.level}级！请选择一个成长方向：`,
                selectedPerks.map(perk => ({
                    text: `${perk.name} - ${perk.description}`,
                    action: () => {
                        perk.effect(character);
                        logMessage(`${character.fullName}选择了${perk.name}！`);
                        hideEventPopup();
                        renderMap();
                    }
                }))
            );
        }

        // 更新技能冷却
        function updateAbilityCooldowns() {
            gameState.characters.forEach(character => {
                if (character.abilities) {
                    character.abilities.forEach(ability => {
                        if (ability.currentCooldown > 0) {
                            ability.currentCooldown--;
                        }
                    });
                }
            });
        }

        // 结束玩家回合
        function endPlayerTurn() {
            // 如果游戏结束，不执行任何操作
            if (gameState.gameOver) return;
            
            // 检查是否所有玩家都已行动
            const unmovedPlayers = gameState.characters
                .filter(char => char.type === CHARACTER_TYPES.PLAYER && !char.moved);
                
            if (unmovedPlayers.length > 0 && gameState.turn === 'player') {
                if (!confirm(`还有${unmovedPlayers.length}名武将未行动，确定要结束回合吗？`)) {
                    return;
                }
            }
            
            // 处理角色的再生效果
            gameState.characters
                .filter(char => char.type === CHARACTER_TYPES.PLAYER && char.regeneration)
                .forEach(character => {
                    const healAmount = character.regeneration;
                    character.hp = Math.min(character.maxHp, character.hp + healAmount);
                    if (healAmount > 0) {
                        logMessage(`${character.fullName}恢复了${healAmount}点生命值！`);
                        // 在角色位置显示治疗效果
                        setTimeout(() => {
                            showHealIndicator(character.x, character.y, healAmount);
                        }, 500);
                    }
                });
            
            // 处理临时属性效果
            gameState.characters.forEach(character => {
                if (character.temporaryDefenseDuration > 0) {
                    character.temporaryDefenseDuration--;
                    if (character.temporaryDefenseDuration === 0) {
                        character.temporaryDefense = 0;
                        logMessage(`${character.fullName}的临时防御加成消失了！`);
                    }
                }
                
                // 解除震慑效果
                if (character.stunned) {
                    character.stunned = false;
                }
            });
            
            logMessage('玩家回合结束');
            
            // 播放回合结束音效
            SoundManager.play('turn');
            
            // 重置所有玩家的移动状态
            gameState.characters
                .filter(char => char.type === CHARACTER_TYPES.PLAYER)
                .forEach(char => char.moved = false);
            
            // 更新技能冷却
            updateAbilityCooldowns();
            
            gameState.turn = 'enemy';
            showInfo('敌人回合...');
            document.getElementById('turn-indicator').textContent = '敌人回合';
            document.getElementById('turn-indicator').className = 'px-3 py-1 bg-red-500 text-white text-sm rounded-full';
            
            // 延迟执行敌人AI，让玩家有时间看到
            setTimeout(enemyTurn, 1000);
        }

        // 敌人回合 - 优化AI
        function enemyTurn() {
            // 如果游戏结束，不执行任何操作
            if (gameState.gameOver) return;
            
            const enemies = gameState.characters.filter(char => char.type === CHARACTER_TYPES.ENEMY);
            const players = gameState.characters.filter(char => char.type === CHARACTER_TYPES.PLAYER);
            
            if (enemies.length === 0) {
                gameState.turn = 'player';
                return;
            }
            
            // 逐个敌人行动，添加延迟以获得更好的视觉效果
            let delay = 0;
            enemies.forEach(enemy => {
                delay += 1000; // 每个敌人之间间隔1秒
                setTimeout(() => {
                    if (gameState.turn !== 'enemy' || gameState.gameOver) return; // 确保还是敌人回合
                    
                    // 如果被震慑，无法行动
                    if (enemy.stunned) {
                        logMessage(`${enemy.fullName}被震慑了，无法行动！`);
                        
                        // 如果是最后一个敌人，结束敌人回合
                        if (enemy === enemies[enemies.length - 1]) {
                            setTimeout(endEnemyTurn, 1000);
                        }
                        return;
                    }
                    
                    // 找到最合适的目标（血量最少的玩家）
                    let targetPlayer = null;
                    let lowestHpPercent = Infinity;
                    
                    players.forEach(player => {
                        const hpPercent = player.hp / player.maxHp;
                        if (hpPercent < lowestHpPercent) {
                            lowestHpPercent = hpPercent;
                            targetPlayer = player;
                        }
                    });
                    
                    if (!targetPlayer) return;
                    
                    // 检查是否可以使用技能
                    let usedAbility = false;
                    if (enemy.abilities && enemy.abilities.length > 0) {
                        // 检查是否有可用技能
                        const availableAbilities = enemy.abilities.filter(ability => ability.currentCooldown === 0);
                        
                        if (availableAbilities.length > 0) {
                            // 根据不同敌人AI选择使用的技能
                            if (enemy.fullName === '曹操' && availableAbilities.some(a => a.name === '号令')) {
                                // 曹操使用号令技能提升周围友军攻击力
                                const nearbyEnemies = enemies.filter(e => 
                                    Math.max(Math.abs(e.x - enemy.x), Math.abs(e.y - enemy.y)) <= 1
                                );
                                
                                if (nearbyEnemies.length > 1) {
                                    nearbyEnemies.forEach(e => {
                                        e.temporaryAttack = (e.temporaryAttack || 0) + 3;
                                        e.temporaryAttackDuration = 1;
                                    });
                                    
                                    logMessage(`${enemy.fullName}使用了号令技能，提升了周围友军的攻击力！`);
                                    availableAbilities.find(a => a.name === '号令').currentCooldown = availableAbilities.find(a => a.name === '号令').cooldown;
                                    usedAbility = true;
                                }
                            } else if (enemy.fullName === '夏侯惇' && availableAbilities.some(a => a.name === '奋不顾身') && 
                                      Math.max(Math.abs(targetPlayer.x - enemy.x), Math.abs(targetPlayer.y - enemy.y)) <= 1) {
                                // 夏侯惇使用奋不顾身技能
                                const damage = Math.floor(enemy.attack * 1.8 - Math.floor(targetPlayer.defense / 3));
                                targetPlayer.hp -= damage;
                                enemy.hp = Math.max(1, enemy.hp - Math.floor(damage * 0.3));
                                
                                showDamageIndicator(targetPlayer.x, targetPlayer.y, damage);
                                showDamageIndicator(enemy.x, enemy.y, Math.floor(damage * 0.3));
                                
                                logMessage(`${enemy.fullName}使用了奋不顾身技能，对${targetPlayer.fullName}造成${damage}点伤害，但自身也受到了伤害！`);
                                
                                // 受伤动画
                                const playerElement = document.querySelector(`.character[data-id="${targetPlayer.id}"]`);
                                if (playerElement) {
                                    playerElement.classList.add('character-hurt');
                                }
                                
                                const enemyElement = document.querySelector(`.character[data-id="${enemy.id}"]`);
                                if (enemyElement) {
                                    enemyElement.classList.add('character-hurt');
                                }
                                
                                // 检查玩家是否被击败
                                if (targetPlayer.hp <= 0) {
                                    handlePlayerDeath(targetPlayer);
                                }
                                
                                availableAbilities.find(a => a.name === '奋不顾身').currentCooldown = availableAbilities.find(a => a.name === '奋不顾身').cooldown;
                                usedAbility = true;
                            }
                        }
                    }
                    
                    if (!usedAbility) {
                        // 如果在攻击范围内，就攻击
                        const distance = Math.max(Math.abs(targetPlayer.x - enemy.x), Math.abs(targetPlayer.y - enemy.y));
                        if (distance <= 1) {
                            // 计算伤害，考虑防御和临时加成
                            let damage = Math.max(1, (enemy.attack + (enemy.temporaryAttack || 0)) - Math.floor((targetPlayer.defense + (targetPlayer.temporaryDefense || 0)) / 3) - Math.floor(Math.random() * 3));
                            
                            targetPlayer.hp -= damage;
                            
                            // 显示伤害数字
                            showDamageIndicator(targetPlayer.x, targetPlayer.y, damage);
                            
                            // 添加受伤动画
                            const playerElement = document.querySelector(`.character[data-id="${targetPlayer.id}"]`);
                            if (playerElement) {
                                playerElement.classList.add('character-hurt');
                            }
                            
                            logMessage(`${enemy.fullName}攻击了${targetPlayer.fullName}，造成${damage}点伤害!`);
                            
                            // 播放攻击和被击中音效
                            SoundManager.play('attack');
                            setTimeout(() => SoundManager.play('hit'), 300);
                            
                            // 检查玩家是否被击败
                            if (targetPlayer.hp <= 0) {
                                handlePlayerDeath(targetPlayer);
                            }
                            
                            renderMap();
                        } 
                        // 否则移动靠近
                        else {
                            // 智能AI：向玩家方向移动一步，优先选择安全路径
                            const path = findShortestPath(enemy.x, enemy.y, targetPlayer.x, targetPlayer.y);
                            
                            if (path && path.length > 1) {
                                const nextStep = path[1];
                                const newX = nextStep.x;
                                const newY = nextStep.y;
                                
                                enemy.x = newX;
                                enemy.y = newY;
                                logMessage(`${enemy.fullName}移动到了(${newX}, ${newY})`);
                                
                                // 添加移动动画
                                const enemyElement = document.querySelector(`.character[data-id="${enemy.id}"]`);
                                if (enemyElement) {
                                    enemyElement.classList.add('character-moving');
                                }
                                
                                renderMap();
                            } else {
                                // 如果找不到路径，尝试简单移动
                                const dx = targetPlayer.x > enemy.x ? 1 : (targetPlayer.x < enemy.x ? -1 : 0);
                                const dy = targetPlayer.y > enemy.y ? 1 : (targetPlayer.y < enemy.y ? -1 : 0);
                                
                                const newX = enemy.x + dx;
                                const newY = enemy.y + dy;
                                
                                // 检查新位置是否有效
                                if (newX >= 0 && newX < GAME_CONFIG.mapSize && newY >= 0 && newY < GAME_CONFIG.mapSize) {
                                    if (gameState.map[newY][newX].type !== CELL_TYPES.OBSTACLE && !getCharacterAtPosition(newX, newY)) {
                                        // 播放移动音效
                                        SoundManager.play('move');
                                        
                                        enemy.x = newX;
                                        enemy.y = newY;
                                        logMessage(`${enemy.fullName}移动到了(${newX}, ${newY})`);
                                        
                                        // 添加移动动画
                                        const enemyElement = document.querySelector(`.character[data-id="${enemy.id}"]`);
                                        if (enemyElement) {
                                            enemyElement.classList.add('character-moving');
                                        }
                                        
                                        renderMap();
                                    }
                                }
                            }
                        }
                    }
                    
                    // 如果是最后一个敌人，结束敌人回合
                    if (enemy === enemies[enemies.length - 1]) {
                setTimeout(endEnemyTurn, 1000);
            }
        }, delay);
    });
}

// 结束敌人回合
function endEnemyTurn() {
    // 如果游戏结束，不执行任何操作
    if (gameState.gameOver) return;
    
    // 处理临时属性效果
    gameState.characters.forEach(character => {
        if (character.temporaryAttackDuration > 0) {
            character.temporaryAttackDuration--;
            if (character.temporaryAttackDuration === 0) {
                character.temporaryAttack = 0;
            }
        }
    });
    
    // 更新技能冷却
    updateAbilityCooldowns();
    
    logMessage('敌人回合结束');
    gameState.turn = 'player';
    showInfo('玩家回合，请选择行动');
    document.getElementById('turn-indicator').textContent = '玩家回合';
    document.getElementById('turn-indicator').className = 'px-3 py-1 bg-primary text-white text-sm rounded-full';
    
    // 检查是否所有玩家都已被击败
    checkDefeat();
    
    renderMap();
}

// 处理玩家死亡
function handlePlayerDeath(player) {
    logMessage(`${player.fullName}被击败了!`);
    
    // 添加死亡动画
    const playerElement = document.querySelector(`.character[data-id="${player.id}"]`);
    if (playerElement) {
        playerElement.classList.add('character-dying');
    }
    
    // 延迟移除死亡单位
    setTimeout(() => {
        gameState.characters = gameState.characters.filter(char => char.id !== player.id);
        renderMap();
        
        // 检查是否游戏结束
        checkDefeat();
    }, 1000);
    
    SoundManager.play('defeat');
}

// 检查是否胜利
function checkVictory() {
    const remainingEnemies = gameState.characters.filter(char => char.type === CHARACTER_TYPES.ENEMY);
    
    if (remainingEnemies.length === 0) {
        logMessage(`第${gameState.level}关胜利！`);
        showNotification(`恭喜！第${gameState.level}关胜利！`);
        SoundManager.play('victory');
        
        gameState.gameOver = true;
        
        // 显示胜利弹窗
        setTimeout(() => {
            showEventPopup(
                '胜利！',
                `恭喜你通过了第${gameState.level}关！准备进入下一关？`,
                [
                    {
                        text: '进入下一关',
                        action: () => {
                            hideEventPopup();
                            gameState.level++;
                            gameState.seed = Math.random(); // 新的随机种子
                            gameState.gameOver = false;
                            
                            // 保留玩家角色，但恢复生命值
                            const players = gameState.characters.filter(char => char.type === CHARACTER_TYPES.PLAYER);
                            players.forEach(player => {
                                player.hp = Math.floor(player.maxHp * 0.8); // 恢复80%生命值
                                player.moved = false;
                            });
                            
                            // 生成新地图和敌人
                            generateMap();
                            spawnCharacters(); // 这会保留玩家角色
                            renderMap();
                            updateGameInfo();
                            
                            logMessage(`开始第${gameState.level}关！`);
                            showNotification(`第${gameState.level}关开始！`);
                        }
                    },
                    {
                        text: '重新开始',
                        action: () => {
                            hideEventPopup();
                            initGame();
                        }
                    }
                ]
            );
        }, 1000);
    }
}

// 检查是否失败
function checkDefeat() {
    const remainingPlayers = gameState.characters.filter(char => char.type === CHARACTER_TYPES.PLAYER);
    
    if (remainingPlayers.length === 0) {
        logMessage('游戏结束，你失败了！');
        showNotification('游戏结束，你失败了！');
        gameState.gameOver = true;
        SoundManager.play('defeat');
        
        // 显示失败弹窗
        setTimeout(() => {
            showEventPopup(
                '失败',
                `在第${gameState.level}关被击败了！是否重新开始？`,
                [
                    {
                        text: '重新开始',
                        action: () => {
                            hideEventPopup();
                            initGame();
                        }
                    }
                ]
            );
        }, 1000);
    }
}

// 更新关卡进度
function updateLevelProgress() {
    const totalEnemies = GAME_CONFIG.enemyCount + Math.max(0, Math.floor(gameState.level / 2) - 1);
    const remainingEnemies = gameState.characters.filter(char => char.type === CHARACTER_TYPES.ENEMY).length;
    const defeatedEnemies = totalEnemies - remainingEnemies;
    
    gameState.levelProgress = Math.min(100, Math.round((defeatedEnemies / totalEnemies) * 100));
    
    document.getElementById('level-progress').style.width = `${gameState.levelProgress}%`;
    document.getElementById('progress-text').textContent = `${gameState.levelProgress}%`;
    document.getElementById('enemy-count').textContent = remainingEnemies;
}

// 更新游戏信息
function updateGameInfo() {
    document.getElementById('level').textContent = gameState.level;
    updateLevelProgress();
}

// 显示信息
function showInfo(text) {
    document.getElementById('selected-info').innerHTML = text;
}

// 显示通知
function showNotification(message) {
    const notification = document.getElementById('notification');
    notification.textContent = message;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 添加日志信息
function logMessage(message) {
    const logContainer = document.getElementById('game-log');
    const logEntry = document.createElement('div');
    
    // 添加时间戳
    const time = new Date();
    const timeString = `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`;
    
    logEntry.innerHTML = `<span class="text-gray-500">[${timeString}]</span> ${message}`;
    logContainer.appendChild(logEntry);
    
    // 滚动到底部
    logContainer.scrollTop = logContainer.scrollHeight;
}

// 寻路算法 - 优化AI路径
function findShortestPath(startX, startY, endX, endY) {
    // 使用BFS寻找最短路径
    const queue = [[{x: startX, y: startY}]];
    const visited = new Set([`${startX},${startY}`]);
    
    // 四个方向
    const directions = [
        {dx: 0, dy: 1},
        {dx: 1, dy: 0},
        {dx: 0, dy: -1},
        {dx: -1, dy: 0}
    ];
    
    while (queue.length > 0) {
        const path = queue.shift();
        const current = path[path.length - 1];
        
        // 如果到达目标
        if (current.x === endX && current.y === endY) {
            return path;
        }
        
        // 探索四个方向
        for (const dir of directions) {
            const x = current.x + dir.dx;
            const y = current.y + dir.dy;
            
            // 检查是否在地图范围内
            if (x >= 0 && x < GAME_CONFIG.mapSize && y >= 0 && y < GAME_CONFIG.mapSize) {
                // 检查是否已经访问过
                const key = `${x},${y}`;
                if (!visited.has(key)) {
                    // 检查是否是障碍物
                    if (gameState.map[y][x].type !== CELL_TYPES.OBSTACLE) {
                        // 检查是否有角色
                        const hasCharacter = getCharacterAtPosition(x, y);
                        if (!hasCharacter || (x === endX && y === endY)) {
                            visited.add(key);
                            const newPath = [...path, {x, y}];
                            queue.push(newPath);
                        }
                    }
                }
            }
        }
    }
    
    // 找不到路径
    return null;
}

// 随机数生成器 - 用于地图生成的一致性
function mulberry32(seed) {
    return function() {
        seed += 0x6D2B79F5;
        let t = seed;
        t = Math.imul(t ^ t >>> 15, t | 1);
        t ^= t + Math.imul(t ^ t >>> 7, t | 61);
        return ((t ^ t >>> 14) >>> 0) / 4294967296;
    }
}

// 页面加载完成后初始化游戏
window.addEventListener('DOMContentLoaded', initGame);
    </script>
</body>
</html>